package com.company.fastsbapi.controller;

import com.company.fastsbapi.dataobject.model.Person;
import com.company.fastsbapi.dataobject.ro.PersonAddRO;
import com.company.fastsbapi.dataobject.ro.PersonUpdateRO;
import com.company.fastsbapi.dataobject.vo.PersonVO;
import com.company.fastsbapi.dataobject.vo.ResultVO;
import com.company.fastsbapi.service.PersonService;
import com.company.fastsbapi.utils.ListBeanConvertUtil;
import com.company.fastsbapi.utils.ROValidUtil;
import com.company.fastsbapi.utils.ResultVOUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;

/**
* Created by CodeGenerator on 2020/09/08.
*/
@RestController
@RequestMapping("/person")
public class PersonController {

    @Autowired
    private PersonService personService;

    @PostMapping
    public ResultVO add(@Valid @RequestBody PersonAddRO personAddRO, BindingResult result) {
        ROValidUtil.valid(result);
        personService.addPerson(personAddRO);
        return ResultVOUtil.returnSuccess();
    }

    @DeleteMapping("/{id}")
    public ResultVO delete(@PathVariable Integer id) {
    personService.deletePerson(id);
    return ResultVOUtil.returnSuccess();
    }

    @PutMapping
    public ResultVO update(@RequestBody PersonUpdateRO personUpdateRO) {
        personService.updatePerson(personUpdateRO);
        return ResultVOUtil.returnSuccess();
    }

    @GetMapping("/{id}")
    public ResultVO detail(@PathVariable Integer id) {
        Person person = personService.findPerson(id);
        PersonVO personVO = new PersonVO();
        BeanUtils.copyProperties(person, personVO);
        return ResultVOUtil.returnSuccess("person", personVO);
    }

    @GetMapping
    public ResultVO list(@RequestParam(defaultValue = "0") Integer page, @RequestParam(defaultValue = "10") Integer size) {
        PageRequest pageRequest = new PageRequest(page, size);
        Page<Person> personPage = personService.findPersonPage(pageRequest);
        List<Person> personList = personPage.getContent();
        List<PersonVO> personVOList = ListBeanConvertUtil.convert(personList, PersonVO.class);
        return ResultVOUtil.returnSuccess("person_list", personVOList);
    }

}